#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:Charmander

import HTMLTestRunner
import os
import unittest

from Advisement_player import readConfig as readConfig
from Advisement_player.common.log import MyLog as Log
from Advisement_player.common.configEmail import TestEmail


class AllTest:

    def __init__(self):
        global log, logger, resultPath
        log = Log.get_log()
        logger = log.get_logger()
        resultPath = log.get_report_path()
        self.caseList = []
        self.caseFile = os.path.join(readConfig.proDir, 'testCase')
        self.caseListFile = os.path.join(readConfig.proDir, 'caselist.txt')
        self.email = TestEmail.get_email()

    #从caselist.txt中读取测试用例
    def set_case_list(self):
        fb = open(self.caseListFile)
        for value in fb.readlines():
            data = str(value)
            if data != '' and not data.startswith('#'):
                self.caseList.append(data.replace('\n',''))
        fb.close()

    #运行测试用例，并返回结果
    def set_case_suite(self):
        self.set_case_list()
        test_suite = unittest.TestSuite()
        suite_module = []

        for case in self.caseList:
            case_name = case.split('/')[-1]
            print(case_name+'.py')
            #批量调用用例
            discover = unittest.defaultTestLoader.discover(self.caseFile,pattern=case_name + '.py', top_level_dir=None)
            suite_module.append(discover)
            print(suite_module)

        if len(suite_module) > 0 :
            for suite in suite_module:
                for test_name in suite:
                    test_suite.addTest(test_name)
        else:
            return None

        return test_suite


    def run(self):
        try:
            suit = self.set_case_suite()
            #创建测试报告
            fp = open(resultPath,'wb')
            if suit is not None:
                logger.info('********TEST START********')
                runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='Test Report',description='Test Description')
                runner.run(suit)
            else:
                logger.info('Have no case to test.')
            fp.close()
        except Exception as ex:
            logger.error(str(ex))
        finally:
            logger.info('********TEST END********')
            self.email.send_email()


if __name__ == '__main__':
    obj = AllTest()
    obj.run()